package io.oschina.binv.kapp.framework.extend

import android.support.v4.view.GestureDetectorCompat
import android.support.v7.widget.*
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.support.v7.widget.OrientationHelper.createVerticalHelper
import android.support.v7.widget.OrientationHelper.createHorizontalHelper
import android.support.v4.view.ViewCompat.canScrollHorizontally
import android.support.v4.view.ViewCompat.canScrollVertically




/**
 * Created by xuybin on 2017/9/12.
 */

fun RecyclerView.scrollBottom(onBottomListener:()->Unit):RecyclerView{
    val recyclerView=this
    this.addOnScrollListener(object :RecyclerView.OnScrollListener(){
        /**
         * 最后一个可见的item的位置
         */
        private var lastVisibleItemPosition: Int = 0

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            val layoutManager = recyclerView.layoutManager
            when (recyclerView.layoutManager) {
                is LinearLayoutManager -> lastVisibleItemPosition = (layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
                is GridLayoutManager -> lastVisibleItemPosition = (layoutManager as GridLayoutManager).findLastVisibleItemPosition()
                is StaggeredGridLayoutManager -> lastVisibleItemPosition =  (layoutManager as StaggeredGridLayoutManager).findLastVisibleItemPositions(null)?.max()?:0
            }
        }

        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            val layoutManager = recyclerView.getLayoutManager()
            val visibleItemCount = layoutManager.childCount
            val totalItemCount = layoutManager.itemCount
            if (visibleItemCount > 0 && newState === RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition >= totalItemCount - 1) {
                //Log.d(TAG, "is loading more");
                onBottomListener()
            }
        }
    })
    return recyclerView
}

fun RecyclerView.itemClick(onItemClickListener:(vh:RecyclerView.ViewHolder )->Unit):RecyclerView{
    val recyclerView=this
    recyclerView.addOnItemTouchListener(object :RecyclerView.SimpleOnItemTouchListener(){
        var mGestureDetector = GestureDetectorCompat(recyclerView.context , object : GestureDetector.SimpleOnGestureListener() {
            override fun onSingleTapUp(e: MotionEvent): Boolean {
                val childView = recyclerView.findChildViewUnder(e.x, e.y)
                if (childView != null) {
                    val vh = recyclerView.getChildViewHolder(childView)////vh.getAdapterPosition();//当前item的位置
                    onItemClickListener(vh)
                }
                return true
            }
        })

        //点击事件交给mGestureDetector处理
        override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
            mGestureDetector.onTouchEvent(e)
            return false
        }
    })
    return recyclerView
}

fun RecyclerView.itemLongClick(onItemLongClickListener:(vh:RecyclerView.ViewHolder )->Unit):RecyclerView{
    val recyclerView=this
    recyclerView.addOnItemTouchListener(object :RecyclerView.SimpleOnItemTouchListener(){
        var mGestureDetector = GestureDetectorCompat(recyclerView.context , object : GestureDetector.SimpleOnGestureListener() {
            override fun onLongPress(e: MotionEvent) {
                val childView = recyclerView.findChildViewUnder(e.x, e.y)
                if (childView != null) {
                    val vh = recyclerView.getChildViewHolder(childView)
                    onItemLongClickListener(vh)//vh.getAdapterPosition();//当前item的位置
                }
            }
        })

        //点击事件交给mGestureDetector处理
        override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
            mGestureDetector.onTouchEvent(e)
            return false
        }
    })
    return recyclerView
}

fun RecyclerView.pagerSnap(firstPosition:Int=0,pagerSnapListener:(targetPosition:Int)->Unit):RecyclerView{
    val recyclerView=this
    val layoutManager= LinearLayoutManager(context)
    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL)
    recyclerView.layoutManager=layoutManager
    object : PagerSnapHelper() {
        override fun findTargetSnapPosition(layoutManager: RecyclerView.LayoutManager, velocityX: Int, velocityY: Int): Int {
            var targetPos = super.findTargetSnapPosition(layoutManager, velocityX, velocityY)
            if(targetPos>0 && targetPos<recyclerView.adapter.itemCount) pagerSnapListener(targetPos)
            return targetPos
        }
    }.attachToRecyclerView(recyclerView)
    pagerSnapListener(firstPosition)
    return recyclerView
}

fun RecyclerView.startSnap(orientation:Int):RecyclerView{
    val recyclerView=this
    val layoutManager= LinearLayoutManager(context)
    layoutManager.setOrientation(orientation)
    recyclerView.layoutManager=layoutManager
    object : LinearSnapHelper () {
        private var mHorizontalHelper: OrientationHelper? = null
        private var mVerticalHelper:OrientationHelper? = null

        override fun calculateDistanceToFinalSnap(layoutManager: RecyclerView.LayoutManager, targetView: View): IntArray {
            val out = IntArray(2)
            if (layoutManager.canScrollHorizontally()) {
                out[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager))
            } else {
                out[0] = 0
            }
            if (layoutManager.canScrollVertically()) {
                out[1] = distanceToStart(targetView, getVerticalHelper(layoutManager))
            } else {
                out[1] = 0
            }
            return out
        }
        override fun findSnapView(layoutManager: RecyclerView.LayoutManager): View? {
            if (layoutManager.canScrollVertically()) {
                return findStartView(layoutManager, getVerticalHelper(layoutManager))
            } else if (layoutManager.canScrollHorizontally()) {
                return findStartView(layoutManager, getHorizontalHelper(layoutManager))
            }
            return null
        }

        private fun distanceToStart(targetView: View, helper: OrientationHelper): Int {
            return helper.getDecoratedStart(targetView) - helper.startAfterPadding
        }
        private fun findStartView(layoutManager: RecyclerView.LayoutManager, helper: OrientationHelper): View?{
             val childCount = layoutManager.childCount
             if (childCount == 0) {
                 return null
             }
             var closestChild: View? = null
            if (layoutManager is LinearLayoutManager) {
                val firstChild = layoutManager.findFirstVisibleItemPosition()
                //需要判断是否是最后一个Item，如果是最后一个则不让对齐，以免出现最后一个显示不完全。
                val isLastItem = layoutManager.findLastCompletelyVisibleItemPosition() === layoutManager.getItemCount() - 1

                if (firstChild == RecyclerView.NO_POSITION || isLastItem) {
                    return null
                }

                val child = layoutManager.findViewByPosition(firstChild)
                if (helper.getDecoratedEnd(child) >= helper.getDecoratedMeasurement(child) / 2 && helper.getDecoratedEnd(child) > 0) {
                     closestChild=child
                } else {
                     closestChild=layoutManager.findViewByPosition(firstChild + 1)
                }
            }else{
                closestChild= super.findSnapView(layoutManager)
            }
            return closestChild
        }
        private fun getHorizontalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper {
            if (mHorizontalHelper == null) {
                mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager)
            }
            return mHorizontalHelper!!
        }
        private fun getVerticalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper {
            if (mVerticalHelper == null) {
                mVerticalHelper = OrientationHelper.createVerticalHelper(layoutManager)
            }
            return mVerticalHelper!!

        }
    }.attachToRecyclerView(recyclerView)
    return recyclerView
}

fun RecyclerView.centerSnap(orientation:Int):RecyclerView{
    val recyclerView=this
    val layoutManager= LinearLayoutManager(context)
    layoutManager.setOrientation(orientation)
    recyclerView.layoutManager=layoutManager
    LinearSnapHelper ().attachToRecyclerView(recyclerView)
    return recyclerView
}
